#pragma once
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "errno.hpp"
static const int defaultsock = -1;
static const int completequeuelenth = 32;
class Sock{
public:
    Sock() :_listensock(defaultsock)
    {}
    ~Sock(){
        if(_listensock != defaultsock)  close(_listensock);
    }
public:
    void Socket(){
        //创建套接字
        _listensock = socket(AF_INET,SOCK_STREAM,0);
        if(_listensock == -1){
            logmessage(FATAL,"socket faild,errocode:%d,errostr:%s",errno,strerror(errno));
            exit(SOCKETERRO);
        }
        logmessage(NORMAL,"socket succuss,fd:%d",_listensock);
        //设置端口资源复用
        int opt = 1;
        if(setsockopt(_listensock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof opt) == -1){
            logmessage(WARING,"set reuseport faild,errocode:%d,errostr:%s",errno,strerror(errno));
        }
    }
    void Bind(int port){
        sockaddr_in peer;
        memset(&peer,0,sizeof peer);
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = INADDR_ANY;
        peer.sin_port = htons(port);
        socklen_t len = sizeof peer;
        if(bind(_listensock,(sockaddr*)&peer,len) == -1){
            logmessage(FATAL,"bind faild");
            exit(BINDERRO);
        }
        logmessage(NORMAL,"bind succuss");
    }
    void Listen(){
        
        if(listen(_listensock,completequeuelenth) == -1){
            logmessage(FATAL,"listen faild");
            exit(LISTENERRO);
        }
        logmessage(NORMAL,"listen succuss");
    }
    int Accept(){
        sockaddr_in peer;
        socklen_t len;
        int sock = accept(_listensock,(sockaddr*)&peer,&len);
        if(sock == -1 && errno != EAGAIN){
            logmessage(WARING,"accept faild");
        }else{
            logmessage(NORMAL,"accept succuss");
        }

        return sock;
    }
    int Getsock()
    {
        if(_listensock != defaultsock) return _listensock;
    }
private:
    int _listensock;
};